import React, { useEffect, useState } from 'react'
import {
  Breadcrumb,
  Card,
  Input,
  Button,
  Table,
  Space,
  Switch,
  Pagination,
  Popconfirm
} from 'antd'
import { getUser, setUserState, deleteUser } from '../../api/user'
import { getRoles } from '../../api/roles'
import AddOrEditUser from './AddOrEditUser';
import Message from '../../components/Message';
import SetUserRole from './SetUserRole';
import PageBreadcrumb from '../../components/PageBreadcrumb';

const { Search } = Input;
const showTotal = (total) => `共 ${total} 条`;

const UserList = () => {

  const text = '此操作将永久删除该用户数据, 是否继续?';
  // 表头
  const columns = [
    {
      title: '姓名',
      dataIndex: 'username',
      key: 'username'
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '电话',
      dataIndex: 'mobile',
      key: 'mobile',
    },
    {
      title: '角色',
      dataIndex: 'role_name',
      key: 'role_name',
    },
    {
      title: '状态',
      dataIndex: 'mg_state',
      key: 'mg_state',
      render: (_, record) => (
        <Switch checked={record.mg_state} onChange={() => userStateChange(record)} />
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type='link' onClick={() => handleEdit(record)}>编辑</Button>
          <Popconfirm placement="top" title={text} onConfirm={() => handleDelete(record.id)} okText="确定" cancelText="取消">
            <Button type='link'>删除</Button>
          </Popconfirm>
          <Button type='link' onClick={() => handleSetRole(record)}>分配角色</Button>
        </Space>
      ),
    },
  ];

  const [data, setData] = useState([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [queryInfo, setQueryInfo] = useState({
    query: "",
    pagenum: 1, // 当前的页数
    pagesize: 5, // 当前每页显示多少条数据
  });
  const [isAddOrEdit, setIsAddOrEdit] = useState(false)
  const [userInfo, setUserInfo] = useState({})
  const [isSetRole, setIsSetRole] = useState(false)
  const [rolesList, setRolesList] = useState([])

  useEffect(() => {
    getListData()
  }, [queryInfo])

  useEffect(() => {
    getRoleList()
  }, [])

  // 获取角色列表
  const getRoleList = async () => {
    const data = await getRoles();
    setRolesList(data.map((item) => {
      return {
        id: item.id,
        roleName: item.roleName,
        roleDesc: item.roleDesc,
      };
    }))
  };
  

  // 查询列表
  const getListData = async () => {
    setLoading(true);
    const data = await getUser(queryInfo).finally(() => {
      setLoading(false)
    });

    setData(data.users)
    setTotal(data.total)

  };

  // 搜索
  const onSearch = (value) => {
    setQueryInfo({
      query: value,
      pagenum: 1,
      pagesize: 5
    })
  }

  // 监听页码值的改变
  const handlePagination = (page, pageSize) => {
    setQueryInfo({
      query: queryInfo.query,
      pagenum: page,
      pagesize: pageSize
    })
  }

  // 改变用户状态
  const userStateChange = async (userInfo) => {
    if (userInfo.mg_state) {
      userInfo.mg_state = false
    } else {
      userInfo.mg_state = true
    }
    setLoading(true);
    const data = await setUserState(userInfo).finally(() => {
      setLoading(false);
    });
    Message("success", "更新用户状态成功！");
  }

  // 点击编辑用户
  const handleEdit = (row) => {
    setUserInfo(row)
    setIsAddOrEdit(true)
  };

  // 删除
  const handleDelete = async (id) => {
    await deleteUser(id);
    Message("success", "删除成功");
    getListData();
  }


// 分配角色
  const handleSetRole = (row) => {
    setUserInfo(row)
    setIsSetRole(true)
  };

  // 关闭添加/编辑对话框
  const hideAddOrEdit = (type) => {
    setUserInfo({})
    setIsAddOrEdit(false)
    if (type) {
      getListData()
    }
  }

  // 关闭设置权限对话框
  const hideSetRole = (type) => {
    setUserInfo({})
    setIsSetRole(false)
    if (type) {
      getListData()
    }
  }

  return (
    <>
      <PageBreadcrumb>
        <span>用户管理</span>
        <span>用户列表</span>
      </PageBreadcrumb>

      <Card>
        <Space size="middle">
          <Search placeholder="请输入姓名" onSearch={onSearch} style={{ width: 300 }} />
          <Button type="primary" onClick={() => setIsAddOrEdit(true)}>添加用户</Button>
        </Space>

        <Table
          rowKey="id"
          bordered
          columns={columns}
          dataSource={data}
          pagination={false}
          loading={loading}
        />

        <Pagination
          total={total}
          current={queryInfo.pagenum}
          pageSize={queryInfo.pagesize}
          showSizeChanger
          showTotal={showTotal}
          onChange={handlePagination}
        />

      </Card>

      <AddOrEditUser visible={isAddOrEdit} userInfo={userInfo} onHide={hideAddOrEdit} />

      <SetUserRole visible={isSetRole} userInfo={userInfo} onHide={hideSetRole} rolesList={rolesList}/>
    </>
  )
}

export default UserList
